#include "MainThread.h"
#include <windows.h>
#include "../Utils/LogUtil.h"
#include "../Utils/TimeUtil.h"
#include "../Core/CoreGlobals.h"
#include "../Misc/Crc.h"
#include "../Input/Input.h"



std::atomic_bool GTimeToExit = false;

MainThread::MainThread(std::shared_ptr<std::promise<void>> startPromise) : TaskThread()
{
	mStartPromise = startPromise;
}

uint32 MainThread::Setup(const TCHAR* threadName, ThreadPriority threadPriority)
{
	mThread = new RunnableThread(this, threadName, threadPriority, GMainThreadId);
	Init();
	Run();
	Stop();
	Exit();
	return GMainThreadId;
}

bool MainThread::Init()
{
	assert(TaskThread::Init());

	/*GraphEventArray prejobArray;
	prejobArray.push_back(GraphTask<AsyncGraphTask>::CreateTask().ConstructAndDispatchWhenReady(GGameThreadId, []() {
			LOGI(L"task 1");
		}));
	prejobArray.push_back(GraphTask<AsyncGraphTask>::CreateTask().ConstructAndDispatchWhenReady(GRenderThreadId, []() {
		LOGI(L"task 2");
		}));
	prejobArray.push_back(GraphTask<AsyncGraphTask>::CreateTask().ConstructAndDispatchWhenReady(GMainThreadId, []() {
		LOGI(L"task 3");
		}));
	GraphTask<AsyncGraphTask>::CreateTask(&prejobArray).ConstructAndDispatchWhenReady(GGameThreadId, []() {
		LOGI(L"task 4");
		});*/



	return true;
}

uint32 MainThread::Run()
{
	// unlock other thread to run
	mStartPromise->set_value();

	MSG msg = { 0 };
	while (true)
	{
		ProcessTasksUntilReturn();

		if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
			if (msg.message == WM_QUIT)
			{
				ThreadManager::Get().Stop();
				break;
			}
		}
	}

	return 0;
}

void MainThread::Stop()
{
	TaskThread::Stop();
}

void MainThread::Exit()
{
	TaskThread::Exit();
}
